#!/bin/bash

help() {
  echo "Usage:"
  echo "  zcompose env <service_name> [options...]"
  echo ""
  echo "    -h, --help    Get help"
  echo "    -e, --edit    Edit env file (.env)"
  echo "    -p, --path    Get env file path"
}

core() {
  if [ "$1" = "" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi
  
  local service_name=$1
  local args=${@:2}

  local service_path=$(service::get_path $service_name)
  if [ "$service_path" = "" ]; then
    log::error "[$(timestamp)][service][env] service($service_name) not found"
    exit 1
  fi

  local service_env_path=$service_path/.env
  if [ ! -f $service_env_path ]; then
    log::error "service($service_name) .env file not found"
    exit 1
  fi

  # @TODO
  shift # ignore service_name($1)
  while [[ $# -gt 0 ]]; do
    local key=$1
    local value=$2
    case $key in
      -h | --help)
        help
        shift # past key
        exit 0
        ;;
      -e | --edit)
        vim $service_env_path
        exit 0
        ;;
      -p | --path)
        echo $service_env_path
        exit 0
        ;;
      *)
        echo "ERROR: unknown parameter \"$key\""
        echo ""
        help
        exit 1
        ;;
    esac
  done

  cat $service_env_path
}

run() {
  core $@
}

run $@
